/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-11-03
 * Time: 13:43
 */
//字符串类型阻塞队列
class MyBlockingQueue {
    private String[] data = null;
    //队头
    private int head = 0;
    //队尾
    private int tail = 0;
    //队列元素个数
    private int size = 0;

    public MyBlockingQueue(int num) {
        data = new String[num];
    }
    //入队
    public void put(String elem) throws InterruptedException {
        synchronized(this) {
            while(size >= data.length) {
                //队列满了，需要阻塞
                this.wait();
            }
            data[tail] = elem;
            tail++;
            if(tail >= data.length) {
                tail = 0;
            }
            size++;
            //唤醒空队列
            this.notify();
        }
    }
    //出队
    public String take() throws InterruptedException {
        synchronized(this) {
            while(size == 0) {
                //队列为空，阻塞
                this.wait();
            }
            String tmp = data[head];
            head++;
            if(head >= data.length) {
                head = 0;
            }
            size--;
            //唤醒满队列
            this.notify();
            return tmp;
        }
    }
}
public class Demo1 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread t1 = new Thread(() -> {
            int a = 0;
            while(true) {
                try {
                    queue.put(a + "");
                    System.out.println("添加元素:" + a);
                    a++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            while(true) {
                String tmp = null;
                try {
                    tmp = queue.take();
                    System.out.println("删除元素:" + tmp);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
